package com.mamesoft.medicipazienti.servlet;

import com.mamesoft.medicipazienti.tools.JDBC;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.ResultSet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class ConfermaRichiamiServlet extends HttpServlet {

    private static Logger log = Logger.getLogger(ConfermaRichiamiServlet.class);

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PropertyConfigurator.configure(ConfermaRichiamiServlet.class.getClassLoader().getResource("com/mamesoft/medicipazienti/tools/log4j.properties"));
        Connection connect = null;
        PrintWriter out = null;
        try {
            HttpSession session = request.getSession();
            connect = JDBC.connect();

            DateFormat c = DateFormat.getDateTimeInstance();
            Enumeration<String> parameterNames = request.getParameterNames();
            ArrayList<Integer> ID = new ArrayList();
            while (parameterNames.hasMoreElements()) {
                ID.add(new Integer(parameterNames.nextElement()));
            }
            String query = null;
            ArrayList<String> nome = null, cognome = null, data = null;
            if (!ID.isEmpty()) {
                query = "SELECT paziente.ID AS ID, paziente.nome AS Nome,paziente.cognome AS Cognome, "
                        + "paziente.foto AS Foto, MAX(vaccino.data) AS Data "
                        + "FROM paziente LEFT JOIN vaccino ON (ID = pID) "
                        + "WHERE ID = '" + ID.get(0) + "' ";
                for (int i = 1; i < ID.size(); i++) {
                    query += "OR ID = '" + ID.get(i) + "' ";
                }
                query += "GROUP BY ID ORDER BY Data DESC";
                ResultSet set = JDBC.executeQuery(query, connect);

                nome = new ArrayList<String>();
                cognome = new ArrayList<String>();
                data = new ArrayList<String>();


                while (set.next()) {
                    nome.add(set.getString("Nome"));
                    cognome.add(set.getString("Cognome"));
                    if (set.getTimestamp("Data") != null) {
                        data.add(c.format(set.getTimestamp("Data")));
                    } else {
                        data.add("Nessun vaccino effettuato ad ora");
                    }
                }
            }
            response.setContentType("text/html;charset=UTF-8");
            out = response.getWriter();

            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("    <head>");
            out.println("        <title>Vaccino Manger</title>");
            out.println("        <link rel=\"stylesheet\" type=\"text/css\" href=\"/MediciPazienti/variant-stream.css\" title=\"Variant Stream\" media=\"screen,projection\" />");
            out.println("        <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">       ");
            out.println("    </head>");

            out.println("    <body>");
            out.println("        <div id =\"wrap\">");
            out.println("            <div id=\"header\">");
            out.println("                <div id =\"topmenu\">");
            out.println("                    <p>");
            out.println("                        <a href=\"/MediciPazienti/logout\">Logout</a>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div id=\"title\">");
            out.println("                    <h1>Vaccino Manager</h1><br/>");
            out.println("                    <h2 class =\"slogan\">I tuoi vaccini contano</h2>");
            out.println("                </div>");
            out.println("            </div>");

            out.println("            <div id=\"sidebar\">");
            out.println("               <ul class = \"sidemenu\">");
            out.println("                   <li><a href=\"/MediciPazienti/medico/welcome\">Home</a><li>");
            out.println("                   <li><a class=\"active\" href=\"/MediciPazienti/medico/richiama\">Invia richiami</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/medico/visualizza_storico\">Visualizza Storico</a><li>");
            out.println("                   <li><a href=\"/MediciPazienti/logout\">Logout</a><li>");
            out.println("               </ul>");
            out.println("            </div>");

            out.println("            <div id =\"content\">");
            out.println("                <div id=\"feature\">");
            out.println("                    <p>" + session.getAttribute("last_login") + "</p>");
            out.println("                    </p>");
            out.println("                </div>");
            out.println("                <div class=\"post\">");

            Long time = System.currentTimeMillis();
            session.setAttribute("time", time);
            Date d = new Date(time);

            out.println("<h2>Conferma selezione: " + c.format(d) + "</h2>");

            if (ID.isEmpty()) {
                session.removeAttribute("time");
                out.println("<p>Non è stato selezionato nessun paziente, tornare "
                        + "indietro e rieffettuare la selezione</>");
            } else {
                out.println("<table width=\"500\">");
                out.println("<thead>");
                out.println("   <tr>");
//                    out.println("       <th>Foto</th>");
                out.println("       <th>Paziente</th>");
                out.println("       <th>Data ultimo vaccino</th>");
                out.println("   </tr>");
                out.println("</thead>");
                out.println("<tbody>");
                for (int i = 0; i < nome.size(); i++) {
                    out.println("   <tr>");
//                        out.println("       <td><IMG SRC=\"/MediciPazienti/" + urlFoto.get(i).replace("jpg", "JPG") + "\" WIDTH=\"50\" HEIGHT=\"50\"></td>");
                    out.println("       <td>" + nome.get(i) + " " + cognome.get(i) + "</td>");
                    out.println("       <td>" + data.get(i) + "</td>");
                    out.println("   </tr>");
                }
                out.println("</tbody>");
                out.println("</table>");
                out.println("<form action=\"/MediciPazienti/medico/prepara_lettere\" method=\"POST\">");
                out.println("<br><input type=\"submit\" value=\"Conferma\" />");
                out.println("</form>");

                session.setAttribute("ID", ID);

            }

            out.println("                </div>");
            out.println("            </div>");
            out.println("            <div id=\"footer\">");
            out.println("                <p class=\"centered\">Copyright &copy; 2011 <a href=\"/MediciPazienti/index.html\">Mamesoft</a>");
            out.println("                    Progetto Programmazione per il web A.A.2011/2012</p>");
            out.println("            </div>");
            out.println("        </div>");
            out.println("    </body>");
            out.println("</html>");

        } catch (Exception ex) {
            request.getSession().invalidate();
            if (ex instanceof SQLException) {
                log.error("Database Error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/database_error.html");
            } else {
                log.error("Generic error: " + ex.toString());
                response.sendRedirect("/MediciPazienti/general_error.html");
            }
        } finally {
            if (connect != null) {
                try {
                    connect.close();
                } catch (SQLException ex) {
                    request.getSession().invalidate();
                    log.error("Database Error: " + ex.toString());
                    response.sendRedirect("/MediciPazienti/database_error.html");
                }
            }
            if (out != null) {
                out.close();
            }
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
